package com.zlz.m3u8download.task;

import com.zlz.m3u8download.bean.RunTimeTask;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @Author: zhulinzhong
 * @Date: 2024/11/29
 */
@Slf4j
public class CommonCache {

    private volatile static boolean SHUT_DOWN = false;

    private static final Integer runningNum = 3;

    public static final Map<Long, Long> userTask = new HashMap<>();

    public static final Map<Long, RunTimeTask> runningTasks = new HashMap<>();

    public static final LinkedHashSet<Long> waitingTasks = new LinkedHashSet<>();

    public static final LinkedHashSet<Long> priorityTask = new LinkedHashSet<>();

    public static boolean maxRunning() {
        if (SHUT_DOWN) {
            return true;
        }
        return runningTasks.size() >= runningNum;
    }

    public static void waitTry(Long task) {
        synchronized (CommonCache.class) {
            runningTasks.remove(task);
            priorityTask.add(task);
        }
    }

    public static void success(Long task) {
        synchronized (CommonCache.class) {
            runningTasks.remove(task);
        }
    }

    public static void fastStart(Long taskId, Long userId) {
        log.debug("执行任务:用户:{},任务:{}", userId, taskId);
        synchronized (CommonCache.class) {
            // 防止已经存在
            if (runningTasks.containsKey(taskId)) {
                log.debug("任务已存在:用户:{},任务:{}", userId, taskId);
                return;
            }
            try {
                // 停止调度
                SHUT_DOWN = true;
                // 检查用户是否存在已经执行的任务
                Long currentTaskId = userTask.get(userId);
                if (currentTaskId != null) {
                    // 停止掉自己的任务
                    RunTimeTask runTimeTask = runningTasks.get(currentTaskId);
                    log.debug("正在停止任务:用户:{},任务:{}", userId, currentTaskId);
                    if (runTimeTask != null) {
                        runTimeTask.setRunning(false);
                    }
                }

                // 加入优先队列
                userTask.put(userId, taskId);
                priorityTask.add(taskId);
                log.debug("已加入等待队列等待调度:用户:{},任务:{}", userId, taskId);
            } finally {
                // 开始调度
                SHUT_DOWN = false;
            }
        }
    }
}
